<template>
  <div class="camera-alert-page" v-loading="loading">
    <el-form label-width="auto" inline class="alert-head">
      <el-form-item label="设备">
        <el-select clearable v-model="page.deviceId" placeholder="请选择设备" @change="deviceChange">
          <el-option 
            v-for="item in deviceList" 
            :key="item.deviceId" 
            :label="item.customDeviceName || item.name"
            :value="item.deviceId" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="通道">
        <el-select clearable v-model="page.channelId" placeholder="请选择通道">
          <el-option 
            v-for="item in channelList" 
            :key="item.channelId" 
            :label="item.customChannelName || item.name"
            :value="item.channelId" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="算法类型">
        <el-select clearable v-model="page.algoType" placeholder="请选择算法">
          <el-option 
            v-for="item in algoTypeList" 
            :key="item.algoType"
            :label="item.algoName"
            :value="item.algoType" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker 
          v-model="range" 
          type="datetimerange" 
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss" 
          clearable 
          :editable="false" 
          time-format="HH:mm" 
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getAlertData">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button
          type="danger"
          :disabled="!selected.length"
          @click="removeConfirm"
          title="删除选中的报警记录"
        >
          删除
        </el-button>
      </el-form-item>
    </el-form>

    <div class="alert-body">
      <el-table :data="alertList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="alarmDescribe" label="报警描述" width="200" />
        <el-table-column prop="device" label="设备" width="200" />
        <el-table-column prop="channel" label="通道" width="200" />
        <el-table-column prop="algoType" label="算法类型" width="250" />
        <el-table-column prop="happenTime" label="发生时间" width="180" />
        <el-table-column label="报警图片">
          <template #default="{ row }">
            <el-image 
              :zoom-rate="1.2" 
              :max-scale="7" 
              :min-scale="0.2" 
              fit="contain" 
              :src="getImageUrl(row.imgUrl)"
              :preview-src-list="[getImageUrl(row.imgUrl)]"
              style="width: 60px; height: 40px;"
            />
          </template>
        </el-table-column>
        <el-table-column label="报警视频">
          <template #default="{ row }">
            <span v-if="row.video === ''">加载中...</span>
            <el-image 
              v-else 
              fit="contain" 
              :src="getImageUrl(row.imgUrl)" 
              @click="openVideo(row)"
              style="width: 60px; height: 40px; cursor: pointer;"
            />
          </template>
        </el-table-column>
      </el-table>

      <el-pagination 
        v-model:current-page="page.pageNum" 
        v-model:page-size="page.showNums"
        :page-sizes="[10, 15, 20, 30]"
        background 
        layout="total, sizes, prev, pager, next, jumper" 
        :total="totalPage" 
        @size-change="getAlertData"
        @current-change="getAlertData" 
      />
    </div>

    <el-dialog v-model="show" destroy-on-close width="60%" class="alert-dialog" :title="videoTitle">
      <video ref="player" autoplay controls muted :src="getVideoUrl(currentRow.video)" />
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { warnController, deviceController, modelController } from '@/services/cameraApi'

const loading = ref(false)
const range = ref()
const algoTypeList = ref([])
const alertList = ref([])
const show = ref(false)
const player = ref()
const totalPage = ref(0)
const selected = ref([])

// 查询报警信息条件字段
const page = reactive({
  deviceId: '',
  channelId: '',
  algoType: '',
  startTime: '',
  endTime: '',
  showNums: 10,
  pageNum: 1
})

// 重置表单
function resetForm() {
  page.deviceId = ""
  page.channelId = ""
  page.algoType = ""
  page.startTime = ""
  page.endTime = ""
  range.value = ""
}

// 处理选择变化
function handleSelectionChange(val) {
  selected.value = val
}

// 删除数据
async function removeData() {
  const list = selected.value.map(e => e.eventId)
  try {
    await warnController.delete(list)
    await getAlertData()
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error(error || '删除失败')
  }
}

// 删除确认
async function removeConfirm() {
  try {
    await ElMessageBox.confirm('确定要删除选中的报警记录吗？', '警告', { 
      confirmButtonText: '确定', 
      cancelButtonText: '取消', 
      type: 'warning' 
    })
    await removeData()
  } catch (error) {
    // 用户取消
  }
}

// 查询报警信息
async function getAlertData() {
  try {
    loading.value = true
    const list = range.value
    const query = { ...page }
    if (Array.isArray(list)) {
      const [startTime, endTime] = list
      Reflect.set(query, "startTime", startTime)
      Reflect.set(query, "endTime", endTime)
    }

    const { data, total, msg } = await warnController.list(query)
    ElMessage.success(msg || '查询成功')
    if (Array.isArray(data)) {
      alertList.value = data.map(warn => {
        const { oriVideoUrl, videoUrl } = warn
        const device = deviceMap.get(warn.deviceId)
        const channel = channelMap.get(warn.channelId)
        return {
          ...warn,
          video: videoUrl ? videoUrl : oriVideoUrl ? oriVideoUrl : '',
          device,
          channel
        }
      })
      totalPage.value = total
    }
  } catch (error) {
    ElMessage.error(error || '查询失败')
    alertList.value = []
    totalPage.value = 0
  } finally {
    loading.value = false
  }
}

// 设备列表
const deviceMap = new Map()
const deviceList = ref([])
async function getDevices() {
  try {
    const { data } = await deviceController.getDeviceList({ page: 1, count: 20 })
    if (data && data.list && Array.isArray(data.list)) {
      data.list.forEach(device => {
        const { deviceId, customDeviceName, name } = device
        getChannels(deviceId)
        deviceMap.set(deviceId, customDeviceName || name)
      })
      deviceList.value = data.list
    }
  } catch (error) {
    deviceList.value = []
  }
}

// 选择设备变化
function deviceChange(deviceId) {
  page.channelId = ""
  if (deviceId) {
    channelList.value = channels.get(deviceId) || []
  } else {
    channelList.value = []
  }
}

// 获取通道
const channelMap = new Map()
const channelList = ref([])
const channels = new Map()
async function getChannels(deviceId) {
  try {
    const { data: { list } } = await deviceController.getChannelList({
      page: 1,
      count: 1000,
      deviceId
    })
    if (Array.isArray(list)) {
      channels.set(deviceId, list)
      list.forEach(channel =>
        channelMap.set(channel.channelId, channel.customChannelName || channel.name)
      )
    }
  } catch (error) {
    // 处理错误
  }
}

// 获取全部算法类型
async function getModelList() {
  try {
    const { data } = await modelController.getModel({ page: 1, count: 20 })
    if (Array.isArray(data)) {
      const list = []
      data.forEach(model => {
        const { algos } = model
        if (Array.isArray(algos)) {
          algos.forEach(algo => {
            const item = list.find(e => e.algoId === algo.algoId)
            if (!item) {
              list.push({ algoType: algo.algoType, algoName: algo.algoName })
            }
          })
        }
      })
      algoTypeList.value = list
    } else {
      algoTypeList.value = []
    }
  } catch (error) {
    algoTypeList.value = []
  }
}

const currentRow = ref({})
const videoTitle = ref()

function openVideo(data) {
  currentRow.value = data
  videoTitle.value = data.alarmDescribe
  show.value = true
}

// 获取图片URL
function getImageUrl(url) {
  if (!url) return ''
  // 开发环境使用代理路径，生产环境使用环境变量
  const prefix = import.meta.env.MODE === 'development' ? '/videoapi' : (import.meta.env.VITE_VIDEO_API || '/videoapi')
  const baseUrl = prefix.endsWith('/') ? prefix : `${prefix}/`
  return url.startsWith('http') ? url : `${baseUrl}${url}`
}

// 获取视频URL
function getVideoUrl(url) {
  if (!url) return ''
  // 开发环境使用代理路径，生产环境使用环境变量
  const prefix = import.meta.env.MODE === 'development' ? '/videoapi' : (import.meta.env.VITE_VIDEO_API || '/videoapi')
  const baseUrl = prefix.endsWith('/') ? prefix : `${prefix}/`
  return url.startsWith('http') ? url : `${baseUrl}${url}`
}

// 初始化
getDevices()
getModelList()
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.camera-alert-page {
  width: 100%;
  height: 100%;
  padding: var(--spacing-lg);
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;

  .alert-head {
    width: 100%;
    background-color: var(--background-color-page);
    padding: var(--spacing-md);
    border-radius: var(--border-radius-lg);
    box-shadow: var(--box-shadow-base);

    .el-form-item {
      margin-right: 16px;

      :deep(.el-form-item__label) {
        justify-content: flex-start;
        color: var(--text-color-regular);
        font-weight: var(--font-weight-medium);
      }

      .el-select {
        width: 150px;
      }

      .el-date-picker {
        width: 260px;
      }
    }
  }

  .alert-body {
    width: 100%;
    height: calc(100% - 80px);
    background-color: var(--background-color-page);
    border-radius: var(--border-radius-lg);
    overflow: hidden;
    margin-top: var(--spacing-lg);
    box-shadow: var(--box-shadow-base);

    .el-table {
      width: 100%;
      height: calc(100% - 60px);

      :deep(.el-table__cell) {
        position: static;
      }

      :deep(.el-table__header) {
        background-color: var(--table-header-bg);
      }

      :deep(.el-table__row:hover) {
        background-color: var(--table-row-hover-bg);
      }
    }

    .el-pagination {
      justify-content: flex-end;
      margin-top: var(--spacing-lg);
      margin-bottom: var(--spacing-lg);
      padding-right: var(--spacing-lg);
    }
  }

  :deep(.el-dialog) {
    .el-dialog__header {
      padding: 0;
    }

    &.alert-dialog {
      video {
        width: 100%;
        height: 100%;
        object-fit: fill;
        margin-top: var(--spacing-md);
      }
    }
  }
}
</style>
